/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.restsql.util.collection;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * MultiHashValuedMap implements Map interface.
 * It that can be used for storing multiple BUT unique String values for a single String key.
 * @author dimitris@jmike.gr
 */
public class MultiHashValuedMap extends HashMap<String, Set<String>> implements Map<String, Set<String>> {

    public MultiHashValuedMap() {
        super();
    }

    /**
     * Add a value to the current list of values for the supplied key.
     * @param key
     * @param value
     */
    public void add(String key, String value) {
        if (super.containsKey(key)) {//map already contains key
            super.get(key).add(value);
        } else {//map does not contain key
            Set<String> set = new HashSet<String>();
            set.add(value);
            super.put(key, set);
        }
    }

    /**
     * A shortcut to get a single value for the supplied key.
     * @param key
     * @return
     */
    public String getSingle(String key) {
        Set<String> set = super.get(key);
        if (set != null) {//map contains key
            return set.iterator().next();
        } else {//map does not contain key
            return null;
        }
    }

    /**
     * Counts the values of the designated key.
     * If the designated key does not exists, the function returns 0.
     * @param key
     * @return
     */
    public int valueSize(String key) {
        Set<String> set = super.get(key);
        if (set != null) {//map contains key
            return set.size();
        } else {//map does not contain key
            return 0;
        }
    }

    /**
     * Returns a String array containing the values of the designated key.
     * If the designated key does not exists, the function returns null.
     * @param key
     * @return
     */
    public String[] getArray(String key) {
        Set<String> set = super.get(key);
        if (set != null) {//map contains key
            return set.toArray(new String[0]);
        } else {//map does not contain key
            return null;
        }
    }
}
